package logic

import (
	"context"
	"jdshopuser/api/pkg"
	"net/http"
	"path/filepath"

	"jdshopuser/api/internal/svc"
	"jdshopuser/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type QiNiuYunLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewQiNiuYunLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QiNiuYunLogic {
	return &QiNiuYunLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *QiNiuYunLogic) QiNiuYun(r *http.Request) (resp *types.RegMsgResponse, err error) {
	// todo: 七牛云文件上传

	file, image, err := r.FormFile("image")
	if err != nil {
		return &types.RegMsgResponse{
			Cre:   -1,
			Msg:   "文件获取失败",
			Datra: nil,
		}, err
	}
	//关闭
	defer file.Close()
	//获取后缀
	imgType := filepath.Ext(image.Filename)
	//判断格式
	if !(imgType == ".jpg" || imgType == ".png") {
		return &types.RegMsgResponse{
			Cre:   -2,
			Msg:   "文件格式错误",
			Datra: nil,
		}, err
	}
	//判断大小
	if image.Size > 1024*1024*2 {
		return &types.RegMsgResponse{
			Cre:   -2,
			Msg:   "文件大小不超过2M",
			Datra: nil,
		}, err
	}
	//上传文件
	imgUrl := pkg.QiNiuYun(file, image.Size)

	return &types.RegMsgResponse{
		Cre: 0,
		Msg: "文件上传成功",
		Datra: map[string]interface{}{
			"imgUrl": imgUrl,
		},
	}, err
}
